<template>
  <view class="verulia-layout">
    <!-- 导航栏 -->
    <uv-navbar title="登录" left-icon="" :placeholder="true"></uv-navbar>
    <!-- 内容 -->
    <view class="verulia-layout__body" :style="{ height: getClientHeight() }">
      <view class="login-container">
        <view class="login-content">
          <image src="@/static/images/logo.png" mode="widthFix"></image>
          <view class="title">{{ appConfig.appName }}</view>
        </view>
        <view class="login-body">
          <uv-form ref="form" :model="loginForm" :rules="rules" error-type="toast">
            <uv-form-item v-if="tenantEnabled" prop="tenantId">
              <uv-input v-model="currentTenantName" placeholder="请选择租户" readonly>
                <template #prefix>
                  <uv-icon name="zuhu" custom-prefix="verulia-icon"></uv-icon>
                </template>
                <template #suffix>
                  <uv-picker ref="tenantPicker" :columns="[tenantList]" key-name="companyName" round="15" @confirm="handleSelectTenant"></uv-picker>
                  <uv-button text="选择租户" type="success" size="mini" @click="openTenantPicker"></uv-button>
                </template>
              </uv-input>
            </uv-form-item>
            <uv-form-item prop="username">
              <uv-input v-model="loginForm.username" prefix-icon="account" placeholder="请输入姓名" />
            </uv-form-item>
            <uv-form-item prop="password">
              <uv-input v-model="loginForm.password" :password="!showPassword" prefix-icon="lock" placeholder="请输入密码">
                <template #suffix>
                  <uv-icon :name="showPassword ? `eye-off-outline` : `eye`" size="24" @click="showPassword = !showPassword"></uv-icon>
                </template>
              </uv-input>
            </uv-form-item>
            <uv-form-item prop="code" v-if="captchaEnabled">
              <view style="display: flex">
                <view style="width: 63%;">
                  <uv-input v-model="loginForm.code" type="number" prefix-icon="empty-permission" placeholder="请输入验证码" />
                </view>
                <view class="login-code">
                  <img :src="codeUrl" class="login-code__img" @click="getCode" />
                </view>
              </view>
            </uv-form-item>
          </uv-form>
          <view class="login-btn">
            <uv-button :loading="btnLoading" type="primary" text="登 录" @click="handleLogin"></uv-button>
          </view>

          <!-- 用户协议 -->
          <view class="login-btn text-12">
            <view style="display: inline-flex">
              <checkbox-group @change="handleCheckAgree">
                <label>
                  <checkbox style="transform: scale(0.5)" :checked="isAgree" />
                </label>
              </checkbox-group>
            </view>
            <text style="vertical-align: middle">我已阅读并同意</text>
            <text class="text-green" style="vertical-align: middle" @click="handleToAgreement('user')">《服务协议》</text>
            <text style="vertical-align: middle">和</text>
            <text class="text-green" style="vertical-align: middle" @click="handleToAgreement('privacy')">《隐私协议》</text>
          </view>

          <!-- 快捷登录 -->
          <view class="quick-login">
            <uv-divider text="快捷登录"></uv-divider>
            <view class="quick-login__list">
              <!-- #ifdef MP-WEIXIN -->
              <view class="quick-login__item">
                <uv-icon name="weixin-circle-fill" size="30px" color="#51cf66" @click="handleQuickLogin('wx')"></uv-icon>
              </view>
              <!-- #endif -->
              <!--              <view class="quick-login__item">-->
              <!--                <uv-icon name="qq-circle-fill" size="30px" color="#339af0" @click="handleQuickLogin"></uv-icon>-->
              <!--              </view>-->
            </view>
          </view>
        </view>
      </view>
    </view>

    <vl-privacy-agreement ref="vlPrivacyAgreementRef" v-model="isAgree"></vl-privacy-agreement>
  </view>
</template>

<script setup lang="ts">
import appConfig from '@/appConfig'
import { useUserStore } from '@/store/modules/user.store'
import { getCodeImg, getTenantList } from '@/api/auth.api'
import { TenantVO, LoginData } from '@/api/auth.type'
import to from 'await-to-js';
import { getClientHeight } from '@/core/utils/verulia'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const userStore = useUserStore()

const btnLoading = ref(false)
const codeUrl = ref('')
// 验证码开关
const captchaEnabled = ref(true)
const showPassword = ref(false)
// 租户开关
const tenantEnabled = ref(true)
// 租户列表
const tenantList = ref<TenantVO[]>([])
const tenantPicker = ref()
const currentTenantName = ref('')
/** 是否同意 */
const isAgree = ref(false)
const vlPrivacyAgreementRef = ref()
/** 登录内容 */
const loginForm = ref<LoginData>({
  tenantId: '',
  username: 'admin',
  password: 'admin123',
  code: ''
});
const rules = ref({
  tenantId: [{ required: true, trigger: 'blur', message: '请选择您所属租户' }],
  username: [
    {
      required: true,
      message: '登录用户名不能为空.',
      trigger: ['blur', 'change']
    }],
  password: [
    {
      required: true,
      message: '密码不能为空.',
      trigger: ['blur', 'change']
    }
  ],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
});
const form = ref();

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

/** 账号密码登录 */
const handleLogin = () => {
  btnLoading.value = true
  if (!verifyHasAgree()) {
    /** 弹出 */
    vlPrivacyAgreementRef.value.show()
    btnLoading.value = false;
    return;
  }
  form.value.validate().then(async () => {
    const [err] = await to(userStore.login(loginForm.value))
    if (!err) {
      // 登录成功
      loginSuccess()
    } else {
      // 重新获取验证码
      if (captchaEnabled.value) {
        await getCode();
      }
    }
    btnLoading.value = false
  }).catch(err => {
    console.log(err)
    btnLoading.value = false
  })
}

/** 快捷登录 */
const handleQuickLogin = (type: string) => {
  if (!verifyHasAgree()) {
    vlPrivacyAgreementRef.value.show()
    return;
  }
  if ('wx' === type) {
    // 微信快捷登录
  }
}

/** 登录成功 */
const loginSuccess = () => {
  userStore.getInfo().then(() => {
    proxy?.$tab.reLaunch('home/index')
  })
}

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList();
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId
      currentTenantName.value = tenantList.value[0].companyName
    }
  }
};

const openTenantPicker = () => {
  tenantPicker.value.open()
}

const handleSelectTenant = (e: any) => {
  const { value } = e
  loginForm.value.tenantId = value[0].tenantId
  currentTenantName.value = value[0].companyName
}

/** app用户协议 */
const handleCheckAgree = (e) => {
  const value = e.detail.value
  isAgree.value = value.length > 0
}

const verifyHasAgree = () => {
  // #TODO 预留启用用户协议
  return isAgree.value
}

const handleToAgreement = (type) => {
  proxy?.$tab.navigateTo('/pages/common/agreement/index?type=' + type)
}

onLoad(() => {
  getCode()
  initTenantList()
})
</script>

<style lang="scss" scoped>
.verulia-layout__body {
  background-image: url('/static/svgs/background.svg');
  background-size: cover;
}

.login-container {
  height: 90%;
  //border-radius: 10px;
  //box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
}

.login-content {
  width: 100%;
  font-size: 21px;
  text-align: center;
  padding-top: 15%;
  display: flex;
  align-items: center;
  justify-content: center;

  image {
    border-radius: 4px;
    width: 50px;
    height: 50px;
  }

  .title {
    margin-left: 10px;
  }
}

.login-body {
  margin-top: 8%;
  padding: 20px;
  //border-radius: 10px;
  //box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;

  input {
    height: 40px;
  }
}

.login-code {
  width: 35%;
  height: 38px;
  float: right;

  &__img {
    height: 38px;
    margin-left: 10px;
    width: 100px;
  }
}

.login-btn {
  margin-top: 25px;
}

.quick-login {
  margin-top: 10px;

  &__list {
    display: flex; /* 使列表项也使用Flex布局 */
    flex-wrap: wrap; /* 允许换行，以防图标过多 */
    justify-content: center; /* 确保列表内的图标水平居中 */
    text-align: center; /* 确保文本居中，尽管在Flex布局中这不是必需的 */
  }

  &__item {
    margin: 0 10px;
  }
}
</style>
